//
//  MNDDiscountViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/12.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDDiscountViewController.h"
#import "MNDDiscountModel.h"
#import "MNDDiscountTableViewCell.h"
#import "MNDAlertDiscountReguraViewController.h"
#import "MNDHistoryDiscountViewController.h"
#import "MNDConfirmObainDiscountAlertViewController.h"
#import "SYRefreshControl.h"
#import "MNDLoginUserModel.h"

#define kCellHeight 177

@interface MNDDiscountViewController ()<UITableViewDelegate,UITableViewDataSource>
/* 模型数组 */
@property (strong, nonatomic) NSMutableArray *discountModelArray;

@property (weak, nonatomic) IBOutlet UITableView *discountTabview;

@property (nonatomic, assign) NSInteger perpageNum;

@property (weak, nonatomic) IBOutlet UIView *noDataView;

@property (weak, nonatomic) IBOutlet UIButton *discountButton;

@end

@implementation MNDDiscountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.discountTabview.estimatedRowHeight = 170;
    self.discountTabview.rowHeight = UITableViewAutomaticDimension;
    [self setupUI];
    [self initialBarbuttonItems];
}

-(NSMutableArray *)discountModelArray {
    if (!_discountModelArray) {
        _discountModelArray = [[NSMutableArray alloc] init];
    }
    return _discountModelArray;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationItem.title = @"我的卡券";
//    _perpageNum = 0;
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"使用规则"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(clickUseRegula:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[item];
    }
}

#pragma mark -加载数据

- (void)loadData:(BOOL)isPullDown {

    if (isPullDown) {
        if (self.discountModelArray.count <= 0) {
            [self.view beginLoading];
        }
        _perpageNum = 1;
    } else {
        _perpageNum++;
    }
    __weak typeof(self) weakSelf = self;
    
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"coupon_status": @"1", @"perpage": @(_perpageNum), @"pagesize":@10}];
    
    [APIManager sendRequestWithPath:API_DISCOUNT_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
    
            NSArray *modelArray = [MNDDiscountModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"coupon_list"]];
            
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeNoData hasData:modelArray.count reloadButtonBlock:nil];
                [weakSelf.discountModelArray removeAllObjects];
            }
            [weakSelf.discountModelArray addObjectsFromArray:modelArray];
            if(kCellHeight * weakSelf.discountModelArray.count > (kScreenHeight - 64 - 80)) {
                weakSelf.discountButton.hidden = YES;
                [weakSelf updateTableFooterView];
            }else {
                weakSelf.discountButton.hidden = NO;
                weakSelf.discountTabview.tableFooterView = [[UIView alloc]init];
            }
            NSLog(@"%@",weakSelf.discountModelArray);
            [SYRefreshControl configAfterLoading:weakSelf.discountTabview hasData:modelArray.count];
            
        } else {
            [SYRefreshControl configAfterLoading:weakSelf.discountTabview hasData:YES];
            if (weakSelf.discountModelArray.count <= 0) {
                [weakSelf.view configBlankPage:SYBlankPageTypeError hasData:YES reloadButtonBlock:^(id sender) {
                    [weakSelf loadData:isPullDown];
                }];
            }
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [weakSelf.discountTabview reloadData];
        
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.discountTabview hasData:YES];
        [NetworkProgressHUD showHudNetworkError:error];
        if (weakSelf.discountModelArray.count <= 0) {
            SYBlankPageType blankType = [weakSelf.view blankPageTypeWithError:error];
            [weakSelf.view configBlankPage:blankType hasData:YES reloadButtonBlock:^(id sender) {
                [weakSelf loadData:isPullDown];
            }];
        }
    }];
}

#pragma mark -搭建界面

- (void)setupUI {
    WeakSelf(self);
    [SYRefreshControl configGifMJRefresh:self.discountTabview refreshType:MJRefreshSupportALl beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakself loadData:YES];
    } loadMoreBlock:^{
        [weakself loadData:NO];
    }];
    [self loadData:YES];
}

#pragma mark -UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.discountModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNDDiscountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DiscountCell"];
    MNDDiscountModel *model = self.discountModelArray[indexPath.row];
    
    if ([model.coupon_explain containsString:@"，"]) {
        cell.titleLabel.text = model.coupon_explain;
        if(kScreenWidth < 375){
            cell.titleLabel.font = [UIFont systemFontOfSize:16];
            
        }else{
            cell.titleLabel.font = [UIFont systemFontOfSize:18];
        }
    }else {

        if (model.coupon_explain.length >= 5) {
            NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",model.coupon_explain]];
            [titleStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(0, titleStr.length)];
            [titleStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(titleStr.length-3, 3)];
            cell.titleLabel.attributedText = titleStr;
        }else {
            cell.titleLabel.font = [UIFont systemFontOfSize:30];
            cell.titleLabel.text = model.coupon_explain;
        }
        
    }
    
    cell.validdateLabel.text = model.coupon_remake;
//    cell.titleLabel.text = [NSString stringWithFormat:@"%@", model.coupon_explain];
    cell.statusBtn.tag = indexPath.row + 100;
    NSString *statusStr = [NSString stringWithFormat:@"%@",model.coupon_status_name];
    if ([statusStr isEqualToString:@"未激活"]) {//未激活的优惠券，显示激活，可点击去激活
        statusStr = @"立即激活";
        //添加点击事件，去激活
        cell.statusBtn.userInteractionEnabled = YES;
        [cell.statusBtn addTarget:self action:@selector(clickObtainDiscountBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell.statusBtn setTitleColor:[UIColor colorWithRed:242/255.0 green:108/255.0 blue:69/255.0 alpha:1.0] forState:UIControlStateNormal];
        [cell.statusBtn setBackgroundColor:[UIColor whiteColor]];
        cell.statusBtn.layer.borderWidth = 1;
        cell.statusBtn.layer.borderColor = [UIColor colorWithRed:242/255.0 green:108/255.0 blue:69/255.0 alpha:1.0].CGColor;
        NSString *dataStr = [NSString stringWithFormat:@"%@后过期",model.coupon_activation_validdate];
        cell.dateLabel.text = dataStr;
    } else {//使用中
         cell.statusBtn.userInteractionEnabled = NO;
        [cell.statusBtn setTitleColor:[UIColor colorWithRed:13/255.0 green:148/255.0 blue:249/255.0 alpha:1.0] forState:UIControlStateNormal];
        [cell.statusBtn setBackgroundColor:[UIColor whiteColor]];
        cell.statusBtn.layer.borderWidth = 1;
        cell.statusBtn.layer.borderColor = [UIColor colorWithRed:13/255.0 green:148/255.0 blue:249/255.0 alpha:1.0].CGColor;
        NSString *dataStr = [NSString stringWithFormat:@"%@前可用",model.coupon_valid_end_date];
        cell.dateLabel.text = dataStr;
        
    }
    cell.couponSourceLabel.text = [NSString stringWithFormat:@"%@", model.coupon_source];
    [cell.statusBtn setTitle:statusStr forState:UIControlStateNormal];
    return cell;
}

//使用规则弹窗
- (IBAction)clickUseRegula:(UIButton *)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDAlertDiscountReguraViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDAlertDiscountReguraViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
}

//历史赠利券跳转
- (IBAction)clickHistoryDiscountBtn:(UIButton *)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
    __weak MNDHistoryDiscountViewController *historyDiscountVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDHistoryDiscountViewController"];
    [self.navigationController pushViewController:historyDiscountVC animated:YES];
}

//激活赠利券
- (void)clickObtainDiscountBtn:(UIButton *)sender {
    MNDDiscountModel *discountModel = self.discountModelArray[sender.tag-100];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDConfirmObainDiscountAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDConfirmObainDiscountAlertViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
        //激活赠利券
        [self gotoObtainDiscount:discountModel.coupon_id];
    } forControlEvents:UIControlEventTouchUpInside];
    [alertVC.cancelButton bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];

    } forControlEvents:UIControlEventTouchUpInside];
}

//更新footerview
- (void)updateTableFooterView {
    CGRect rect = self.discountTabview.tableFooterView.bounds;
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectZero];
    [btn setTitle:@"历史卡券 >" forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [btn setTitleColor:[UIColor colorWithHex:0xB5B5B5] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickHistoryDiscountBtn:) forControlEvents:UIControlEventTouchUpInside];
    UIView *footeView = [[UIView alloc]initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 80)];
    [footeView addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(footeView);
        make.bottom.mas_equalTo(footeView).mas_offset(-40);
    }];
    
    self.discountTabview.tableFooterView = footeView;
}

//调用激活赠利券接口
- (void)gotoObtainDiscount:(NSString *)couponId {
    
    WeakSelf(self);
    
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"coupon_id":couponId}];
    
    [APIManager sendRequestWithPath:API_OBTAIN_DISCOUNT parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if(responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"激活成功"];
            //刷新数据
            weakself.perpageNum = 0;
            [weakself loadData:YES];
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
